const router = require("express").Router();
const mysql = require("./../mysql");
const Review = require("./../mysql/collection/Review");
const Order = require("./../mysql/collection/Order");
const uuid = require("uuid");

/**
 * @api {post} /api/review/submit 提交订单评价
 * @apiName submitReview
 * @apiGroup Review
 * @apiHeader {String} token  token
 * @apiParam {String} orderid 订单ID
 * @apiParam {String} userid 用户ID
 * @apiParam {Number} rating 评分（1-5）
 * @apiParam {String} [content] 评价内容
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '评价提交成功',
 *    data: {
 *      reviewid: 'review_xxx',
 *      orderid: 'order_xxx',
 *      userid: 'user_xxx',
 *      rating: 5,
 *      content: '商品质量很好',
 *      created_at: '2024-01-01T00:00:00.000Z'
 *    }
 *  }
 */
router.post("/submit", (req, res, next) => {
  const { orderid, userid, rating, content = '' } = req.body;
  console.log('收到评价提交请求:', { orderid, userid, rating, content });

  // 参数验证
  if (!orderid || !userid || !rating) {
    console.log('参数验证失败: 缺少必要参数');
    return res.send({
      code: "400",
      message: "订单ID、用户ID和评分不能为空"
    });
  }

  if (rating < 1 || rating > 5 || !Number.isInteger(Number(rating))) {
    console.log('参数验证失败: 评分格式错误');
    return res.send({
      code: "400",
      message: "评分必须是1-5之间的整数"
    });
  }

  console.log('开始检查订单是否存在...');
  // 检查订单是否存在且属于该用户
  mysql.find(Order, { orderid, userid })
    .then(orders => {
      console.log('订单查询结果:', orders.length > 0 ? '找到订单' : '未找到订单');
      if (orders.length === 0) {
        console.log('订单不存在或不属于该用户');
        res.send({
          code: "404",
          message: "订单不存在或不属于该用户"
        });
        return Promise.reject('订单不存在'); // 阻止后续执行
      }

      const order = orders[0];
      console.log('订单状态检查:', { orderid, status: order.status });
      // 检查订单状态是否为已完成（status = 4）
      if (order.status !== 4) {
        const statusNames = {
          0: '未支付',
          1: '待发货', 
          2: '待收货',
          3: '待评价'
        };
        console.log('订单状态不符合要求:', order.status);
        res.send({
          code: "400",
          message: `订单状态为${statusNames[order.status]}，只有已完成的订单才能评价`
        });
        return Promise.reject('订单状态不符合'); // 阻止后续执行
      }

      console.log('开始检查是否已评价过...');
      // 检查是否已经评价过
      return mysql.find(Review, { orderid, userid });
    })
    .then(existingReviews => {
      console.log('评价重复检查结果:', existingReviews ? existingReviews.length : 'null');
      if (existingReviews && existingReviews.length > 0) {
        console.log('该订单已经评价过了');
        res.send({
          code: "400",
          message: "该订单已经评价过了"
        });
        return Promise.reject('订单已评价'); // 阻止后续执行
      }

      // 创建评价记录
      const reviewData = {
        reviewid: "review_" + uuid.v4(),
        orderid,
        userid,
        rating: Number(rating),
        content: content.trim(),
        created_at: new Date(),
        updated_at: new Date()
      };
      console.log('准备插入评价数据:', reviewData);

      return mysql.insert(Review, reviewData);
    })
    .then(result => {
      console.log('评价插入成功:', result);
      res.send({
        code: "200",
        message: "评价提交成功",
        data: {
          reviewid: result.reviewid || result.insertId
        }
      });
    })
    .catch(error => {
      // 只有在真正的错误时才发送响应，业务逻辑错误已经在上面处理了
      if (error !== '订单不存在' && error !== '订单状态不符合' && error !== '订单已评价') {
        console.error('评价提交失败:', error);
        console.error('错误堆栈:', error.stack);
        res.send({
          code: "500",
          message: "评价提交失败",
          error: error.message
        });
      }
    });
});

/**
 * @api {get} /api/review/order/:orderid 获取订单评价
 * @apiName getOrderReview
 * @apiGroup Review
 * @apiHeader {String} token  token
 * @apiParam {String} orderid 订单ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取评价成功',
 *    data: {
 *      reviewid: 'review_xxx',
 *      orderid: 'order_xxx',
 *      userid: 'user_xxx',
 *      rating: 5,
 *      content: '商品质量很好',
 *      created_at: '2024-01-01T00:00:00.000Z'
 *    }
 *  }
 */
router.get("/order/:orderid", (req, res, next) => {
  const { orderid } = req.params;
  const { userid } = req.query;

  if (!orderid) {
    return res.send({
      code: "400",
      message: "订单ID不能为空"
    });
  }

  if (!userid) {
    return res.send({
      code: "400",
      message: "用户ID不能为空"
    });
  }

  mysql.find(Review, { orderid, userid }, { _id: 0, __v: 0 })
    .then(reviews => {
      if (reviews.length === 0) {
        return res.send({
          code: "404",
          message: "该订单暂无评价"
        });
      }

      res.send({
        code: "200",
        message: "获取评价成功",
        data: reviews[0]
      });
    })
    .catch(err => {
      console.error('获取订单评价失败:', err);
      res.send({
        code: "500",
        message: "获取订单评价失败"
      });
    });
});

/**
 * @api {get} /api/review/user 获取用户评价列表
 * @apiName getUserReviews
 * @apiGroup Review
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户ID
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取用户评价列表成功',
 *    data: {
 *      list: [],
 *      total: 0,
 *      page: 1,
 *      pageSize: 10
 *    }
 *  }
 */
router.get("/user", (req, res, next) => {
  const { userid, page = 1, pageSize = 10 } = req.query;

  if (!userid) {
    return res.send({
      code: "400",
      message: "用户ID不能为空"
    });
  }

  const pageNum = parseInt(page);
  const pageSizeNum = parseInt(pageSize);
  const skip = (pageNum - 1) * pageSizeNum;

  // 获取总数
  mysql.find(Review, { userid })
    .then(allReviews => {
      const total = allReviews.length;
      
      // 获取分页数据，按创建时间倒序
      return mysql.find(
        Review, 
        { userid }, 
        { _id: 0, __v: 0 },
        { created_at: -1 },
        skip,
        pageSizeNum
      ).then(reviews => {
        // 获取每个评价对应的订单信息
        const orderPromises = reviews.map(review => 
          mysql.find(Order, { orderid: review.orderid }, { 
            orderid: 1, 
            proname: 1, 
            img1: 1, 
            discount: 1, 
            num: 1,
            _id: 0 
          })
        );
        
        return Promise.all(orderPromises).then(orderResults => {
          const reviewsWithOrderInfo = reviews.map((review, index) => {
            const orderInfo = orderResults[index][0] || {};
            return {
              ...review,
              orderInfo: {
                proname: orderInfo.proname || '',
                img1: orderInfo.img1 || '',
                price: orderInfo.discount || 0,
                num: orderInfo.num || 0
              }
            };
          });
          
          res.send({
            code: "200",
            message: "获取用户评价列表成功",
            data: {
              list: reviewsWithOrderInfo,
              total,
              page: pageNum,
              pageSize: pageSizeNum
            }
          });
        });
      });
    })
    .catch(err => {
      console.error('获取用户评价列表失败:', err);
      res.send({
        code: "500",
        message: "获取用户评价列表失败"
      });
    });
});

/**
 * @api {get} /api/review/product/:proid 获取商品评价列表
 * @apiName getProductReviews
 * @apiGroup Review
 * @apiParam {String} proid 商品ID
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [sortBy=created_at] 排序字段 (created_at|rating)
 * @apiParam {String} [sortOrder=desc] 排序方向 (asc|desc)
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取商品评价列表成功',
 *    data: {
 *      list: [
 *        {
 *          reviewid: 'review_xxx',
 *          orderid: 'order_xxx',
 *          userid: 'user_xxx',
 *          rating: 5,
 *          content: '商品质量很好',
 *          created_at: '2024-01-01T00:00:00.000Z',
 *          productInfo: {
 *            proname: '商品名称',
 *            img1: '商品图片'
 *          }
 *        }
 *      ],
 *      total: 100,
 *      page: 1,
 *      pageSize: 10,
 *      avgRating: 4.5
 *    }
 *  }
 */
router.get("/product/:proid", (req, res, next) => {
  const { proid } = req.params;
  const { page = 1, pageSize = 10, sortBy = 'created_at', sortOrder = 'desc' } = req.query;

  if (!proid) {
    return res.send({
      code: "400",
      message: "商品ID不能为空"
    });
  }

  const pageNum = parseInt(page);
  const pageSizeNum = parseInt(pageSize);
  const skip = (pageNum - 1) * pageSizeNum;

  // 验证排序参数
  const validSortFields = ['created_at', 'rating'];
  const validSortOrders = ['asc', 'desc'];
  const finalSortBy = validSortFields.includes(sortBy) ? sortBy : 'created_at';
  const finalSortOrder = validSortOrders.includes(sortOrder) ? sortOrder : 'desc';
  
  // 构建排序对象
  const sortObj = {};
  sortObj[finalSortBy] = finalSortOrder === 'desc' ? -1 : 1;

  console.log('获取商品评价请求:', { proid, page: pageNum, pageSize: pageSizeNum, sortBy: finalSortBy, sortOrder: finalSortOrder });

  // 第一步：通过proid查找所有相关订单
  mysql.find(Order, { proid })
    .then(orders => {
      console.log(`找到商品${proid}的订单数量:`, orders.length);
      
      if (orders.length === 0) {
        return res.send({
          code: "200",
          message: "该商品暂无评价",
          data: {
            list: [],
            total: 0,
            page: pageNum,
            pageSize: pageSizeNum,
            avgRating: 0
          }
        });
      }

      // 提取所有订单ID
      const orderIds = orders.map(order => order.orderid);
      console.log('相关订单IDs:', orderIds);

      // 第二步：通过订单ID查找所有评价
      return mysql.find(Review, { orderid: { $in: orderIds } })
        .then(allReviews => {
          console.log(`找到评价数量:`, allReviews.length);
          
          if (allReviews.length === 0) {
            return res.send({
              code: "200",
              message: "该商品暂无评价",
              data: {
                list: [],
                total: 0,
                page: pageNum,
                pageSize: pageSizeNum,
                avgRating: 0
              }
            });
          }

          const total = allReviews.length;
          
          // 计算平均评分
          const avgRating = allReviews.reduce((sum, review) => sum + review.rating, 0) / total;
          
          // 排序评价
          allReviews.sort((a, b) => {
            if (finalSortBy === 'created_at') {
              const timeA = new Date(a.created_at).getTime();
              const timeB = new Date(b.created_at).getTime();
              return finalSortOrder === 'desc' ? timeB - timeA : timeA - timeB;
            } else if (finalSortBy === 'rating') {
              return finalSortOrder === 'desc' ? b.rating - a.rating : a.rating - b.rating;
            }
            return 0;
          });
          
          // 分页处理
          const paginatedReviews = allReviews.slice(skip, skip + pageSizeNum);
          
          // 第三步：为每个评价添加商品信息
          const reviewsWithProductInfo = paginatedReviews.map(review => {
            // 找到对应的订单信息
            const orderInfo = orders.find(order => order.orderid === review.orderid);
            return {
              reviewid: review.reviewid,
              orderid: review.orderid,
              userid: review.userid,
              rating: review.rating,
              content: review.content,
              created_at: review.created_at,
              updated_at: review.updated_at,
              productInfo: {
                proname: orderInfo ? orderInfo.proname : '',
                img1: orderInfo ? orderInfo.img1 : ''
              }
            };
          });
          
          res.send({
            code: "200",
            message: "获取商品评价列表成功",
            data: {
              list: reviewsWithProductInfo,
              total,
              page: pageNum,
              pageSize: pageSizeNum,
              avgRating: Math.round(avgRating * 10) / 10 // 保留一位小数
            }
          });
        });
    })
    .catch(err => {
      console.error('获取商品评价列表失败:', err);
      res.send({
        code: "500",
        message: "获取商品评价列表失败",
        error: err.message
      });
    });
});

module.exports = router;